const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function showLoading(message) {
  if (wx.showLoading) {
    // 基础库 1.1.0 微信6.5.6版本开始支持，低版本需做兼容处理
    wx.showLoading({
      title: message,
      mask: true
    });
  } else {
    // 低版本采用Toast兼容处理并将时间设为20秒以免自动消失
    wx.showToast({
      title: message,
      icon: 'loading',
      mask: true,
      duration: 20000
    });
  }
}

function hideLoading() {
  if (wx.hideLoading) {
    // 基础库 1.1.0 微信6.5.6版本开始支持，低版本需做兼容处理
    wx.hideLoading();
  } else {
    wx.hideToast();
  }
}

/**
  * 生成海报获取文字
  * @param string text 为传入的文本
  * @param int num 为单行显示的字节长度
  * @return array 
 */
const textByteLength = (text, num) => {
  let strLength = 0;
  let rows = 1;
  let str = 0;
  let arr = [];
  for (let j = 0; j < text.length; j++) {
    if (text.charCodeAt(j) > 255) {
      strLength += 2;
      if (strLength > rows * num) {
        strLength++;
        arr.push(text.slice(str, j));
        str = j;
        rows++;
      }
    } else {
      strLength++;
      if (strLength > rows * num) {
        arr.push(text.slice(str, j));
        str = j;
        rows++;
      }
    }
  }
  arr.push(text.slice(str, text.length));
  return [strLength, arr, rows]   //  [处理文字的总字节长度，每行显示内容的数组，行数]
}
/**
 * 获取分享海报
 * @param array arr2 海报素材
 * @param string snap_name 素材文字
 * @param string price 价格
 * @param function successFn 回调函数
 * 
 * 
*/
const PosterCanvas = (arr2, snap_name, price, numtxt, successFn) => {
  wx.showLoading({ title: '海报生成中', mask: true });
  const ctx = wx.createCanvasContext('myCanvas');
  ctx.clearRect(0, 0, 0, 0);
  /**
   * 只能获取合法域名下的图片信息,本地调试无法获取
   * 
  */
  wx.getImageInfo({
    src: arr2[0],
    success: function (res) {
      const WIDTH = res.width;
      const HEIGHT = res.height;
      ctx.drawImage(arr2[0], 0, 0, WIDTH, HEIGHT);
      ctx.drawImage(arr2[1], 0, 0, WIDTH, 9*WIDTH/10);
      ctx.save();
      let r = 90;
      let d = r * 2;
      let cx = 40;
      let cy = 990;
      ctx.arc(cx + r, cy + r, r, 0, 2 * Math.PI);
      ctx.clip();
      ctx.drawImage(arr2[2], cx, cy, d, d);
      ctx.restore();
      const CONTENT_ROW_LENGTH = 40;
      let [contentLeng, contentArray, contentRows] = textByteLength(snap_name, CONTENT_ROW_LENGTH);
      if (contentRows > 2) {
        contentRows = 2;
        let textArray = contentArray.slice(0, 2);
        textArray[textArray.length - 1] += '……';
        contentArray = textArray;
      }
      //ctx.setTextAlign('center');
      ctx.setFontSize(38);
      let contentHh = 38 * 1.3;
      for (let m = 0; m < contentArray.length; m++) {
        //ctx.fillText(contentArray[m], WIDTH / 2, 820 + contentHh * m);
        ctx.fillText(contentArray[m], 30, 750 + contentHh * m);
      }
      //ctx.setTextAlign('center')
      ctx.setFontSize(32);
      //ctx.setFillStyle('red');
      //ctx.fillText('￥' + price, WIDTH / 2, 860 + contentHh);
      ctx.fillText(numtxt, 30, 780 + contentHh);

      //ctx.setTextAlign('center')
      ctx.setFontSize(32);
      //ctx.setFillStyle('red');
      //ctx.fillText('￥' + price, WIDTH / 2, 860 + contentHh);
      ctx.setFillStyle('#FF6600');
      if (price > 0){
        ctx.fillText('￥' + price, 30, 830 + contentHh);
      }else{
        ctx.fillText('免费', 30, 830 + contentHh);
      }
      
      ctx.draw(true, function () {
        wx.canvasToTempFilePath({
          canvasId: 'myCanvas',
          fileType: 'png',
          destWidth: WIDTH,
          destHeight: HEIGHT,
          success: function (res) {
            wx.hideLoading();
            successFn && successFn(res.tempFilePath);
          }
        })
      });
    },
    fail: function () {
      wx.hideLoading();
      //Tips({ title: '无法获取图片信息' });
    }
  })
}

function compareVersion(v1, v2) {
    v1 = v1.split('.')
    v2 = v2.split('.')
    var len = Math.max(v1.length, v2.length)
    while(v1.length <len) {
      v1.push('0')
    }
    while(v2.length <len) {
      v2.push('0')
    }
    for(var i = 0; i<len; i++) {
    var num1 = parseInt(v1[i])
    var num2 = parseInt(v2[i])
      if (num1 > num2) {
        return 1
      } else if (num1 < num2) {
        return -1
      }
    }
    return 0
  }

module.exports = {
  formatTime: formatTime,
  showLoading: showLoading,
  hideLoading: hideLoading,
  PosterCanvas: PosterCanvas,
  compareVersion:compareVersion
}
